<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handleImport()">
          <Icon icon="i-ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <a-button type="default" @click="handleSyn({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-simple-line-icons:refresh" /> {{ t('同步任务') }}
        </a-button>
        <a-button
          type="default"
          @click="handleGenerateTask({})"
          v-auth="'rd:db:transferorder:edit'"
          v-if="props.ftype == '29'"
        >
          <Icon icon="i-ant-design:download-outlined" /> {{ t('生成下架任务') }}
        </a-button>
        <a-button type="default" @click="handleShdPrint()" >
          <Icon icon="ant-design:printer-twotone" /> {{ t('打印') }}
        </a-button>
        <Popconfirm placement="bottom" :title="t('是否确认撤销？')" @confirm="handleCancel">
          <a-button type="default" v-auth="'wh:rd02:rd02:edit'">
            <!-- <CodeOutlined /> -->
            <Icon icon="ant-design:code-outlined" /> {{ t('撤销') }}
          </a-button>
        </Popconfirm>

        <a-button type="default" @click="handleTs({})" v-auth="'rd:rd10:rdrecord10:edit'">
          <!-- <HighlightOutlined /> -->
          <Icon icon="i-ant-design:highlight-outlined" /> {{ t('手动推送') }}
        </a-button>

        <a-button type="success" ghost @click="handleForm({})" v-auth="'rd:rd08:rdrecord08:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id, isView: true })">
          {{ record.fbillno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <Rd01InputForm @register="registerRd01Drawer" @success="handleSuccess" />
    <BasicModal v-bind="$attrs" @register="registerModal" title="请确认拣货方式" @ok="handleQr">
      <BasicForm @register="registerForm" />
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="ViewsRd08Rdrecord08List">
  import { unref, defineProps, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    rdrecord08Delete,
    rdrecord08ListData,
    rdrecord08Syn,
    batchUpdateDate,
    generateTask,
    rd08Revoke,
  } from '/src/api/wms/rd/rd08/rdrecord08';
  import { Popconfirm } from 'ant-design-vue';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { propTypes } from '/@/utils/propTypes';
  import Rd01InputForm from '/@/views/wms/wh/rd01/rd01/form.vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModal } from '/@/components/Modal';
  import PrintModal from '/@/components/print/printModal.vue';
  import FormImport from './formImport.vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  

  const { t } = useI18n('rd08.rdrecord08');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const userStore = useUserStore();

  const props = defineProps({
    ftype: propTypes.string,
  });

  onMounted(async () => {
    setProps();
    handleCompany();
  });

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('其他出入库管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('单据编号'),
        field: 'fbillno',
        component: 'Input',
      },
      // {
      //   label: t('业务类型'),
      //   field: 'ftype',
      //   component: 'Select',
      //   componentProps: {
      //     dictType: 'wh_rd08_bus_type',
      //     allowClear: true,
      //   },
      // },
      {
        label: t('日期'),
        field: 'fdate',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
      },
      {
        label: t('备注'),
        field: 'fexplanation',
        component: 'Input',
      },
      {
        label: t('制单人'),
        field: 'fbiller',
        component: 'Input',
      },
      {
        label: t('备注'),
        field: 'remarks',
        component: 'Input',
      },
      {
        label: t('总数'),
        field: 'iqty',
        component: 'Input',
      },
      {
        label: t('来源标识'),
        field: 'sourceFlag',
        component: 'Select',
        componentProps: {
          dictType: 'bas_source_type',
          allowClear: true,
        },
      },
      {
        label: t('入库状态'),
        field: 'rkStatus',
        component: 'Select',
        componentProps: {
          dictType: 'wms_rd10_status',
          allowClear: true,
        },
      },
      {
        label: t('状态'),
        field: 'status',
        component: 'Select',
        componentProps: {
          dictType: 'sys_search_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('公司名称'),
      dataIndex: 'companyName',
      key: 'a.company_name',
      sorter: true,
      width: 230,
      align: 'left',
    },
    {
      title: t('单据编号'),
      dataIndex: 'fbillno',
      key: 'a.fbillno',
      sorter: true,
      width: 130,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('业务类型'),
      dataIndex: 'ftype',
      key: 'a.ftype',
      sorter: true,
      width: 130,
      align: 'center',
      dictType: 'wh_rd08_bus_type',
    },
    {
      title: t('状态'),
      dataIndex: 'rkStatus',
      key: 'a.rk_status',
      sorter: true,
      width: 130,
      align: 'center',
      dictType: 'wms_rd10_status',
    },
    {
      title: t('推送'),
      dataIndex: 'bsend',
      key: 'a.bsend',
      sorter: true,
      width: 100,
      align: 'center',
      dictType: 'sys_yes_no',
    },
    {
      title: t('日期'),
      dataIndex: 'fdate',
      key: 'a.fdate',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('备注'),
      dataIndex: 'fexplanation',
      key: 'a.fexplanation',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('制单人'),
      dataIndex: 'fbiller',
      key: 'a.fbiller',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('总数'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('来源标识'),
      dataIndex: 'sourceFlag',
      key: 'a.source_flag',
      sorter: true,
      width: 130,
      align: 'center',
      dictType: 'bas_source_type',
    },

    {
      title: t('更新日期'),
      dataIndex: 'updateDate',
      key: 'a.update_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        label: '入库',
        onClick: handleRd01Form.bind(this, { taskCode: record.id, busType: record.ftype }),
        auth: 'rd:rd08:rdrecord08:edit',
        ifShow: () => props.ftype == '10' && record.rkStatus != '2',
      },
      // {
      //   icon: 'i-ant-design:delete-outlined',
      //   color: 'error',
      //   title: t('删除其他出入库'),
      //   popConfirm: {
      //     title: t('是否确认删除其他出入库'),
      //     confirm: handleDelete.bind(this, record),
      //   },
      //   auth: 'rd:rd08:rdrecord08:edit',
      // },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerRd01Drawer, { openDrawer: openRd01Drawer }] = useDrawer();

  const [registerTable, { reload, getForm, getSelectRows, setProps, getSelectRowKeys }] = useTable({
    api: rdrecord08ListData,
    beforeFetch: (params) => {
      params.ftype = props.ftype;
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleForm(record: Recordable) {
    record.ftype = props.ftype;
    openDrawer(true, record);
  }

  function handleRd01Form(record: Recordable) {
    openRd01Drawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { id: record.id };
    const res = await rdrecord08Delete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/rd/rd08/rdrecord08/exportMainData',
      params: getForm().getFieldsValue(),
    });
  }

  // 同步K3调整单信息
  async function handleSyn() {
    const res = await rdrecord08Syn({});
    showMessage(res.message);
    handleSuccess({});
  }

  async function handleTs() {
    if (getSelectRows().length) {
      const selIds = getSelectRows()
        .map((item) => item.id)
        .join(',');
      const res = await batchUpdateDate({ selIds: selIds });
      showMessage(res.message);
      handleSuccess({});
    } else {
      showMessage('请先选择数据');
    }
  }

  const [registerForm, { validate }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('拣货方式'),
        field: 'type',
        component: 'Select',
        defaultValue: '1',
        componentProps: {
          dictType: 'jh_type',
          // allowClear: true,
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });
  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();
  async function handleGenerateTask() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    openModal(true, {});
    // const selIds = arr.map((item) => item.id).join(',');
    // const params = { selIds: selIds };
    // const res = await generateTask(params);
    // console.log(res, 'res');
    // showMessage(res.message);
    // handleSuccess({});
  }
  async function handleQr() {
    try {
      let dataValidate = await validate();
      setModalProps({ confirmLoading: true });
      const jhPlanAreaList = getSelectRows();
      const ids = jhPlanAreaList.map((item) => item.id).join(',');
      const data: any = {
        ...dataValidate,
        selIds: ids,
      };
      const res = await generateTask(data);
      showMessage(res.message);
      reload();
      closeModal();
      // setTableData3([]);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  async function handleShdPrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择数据'));
      return;
    }
    const ids = getSelectRowKeys().join(',');
    console.log(ids);
    let params = {
      ids: ids,
      title: '其他出入库单',
      height: '0.9',
      width: '0.9',
      fileName: '其他出入库单',
    };
    openPrintModal(true, params);
  }

  async function handleCancel() {
    if (getSelectRowKeys().length == 1) {
      // if (props.ftype == '29') {
      //   // 其它出库
      //   const res = await batchBack({ code: getSelectRowKeys()[0] });
      // } else if (props.ftype == '10') {
      //   // 其它入库
      //   const res = await batchBack({ code: getSelectRowKeys()[0] });
      // }
      const res = await rd08Revoke({ id: getSelectRowKeys()[0], type: props.ftype });
      showMessage(res.message);
      handleSuccess({});
    } else {
      showMessage('请先选择一条数据！');
    }
  }

  const [registerImportModal, { openModal: importModal }] = useModal();
  function handleImport() {
    importModal(true, {
      ftype: props.ftype,
    });
  }

  async function handleCompany() {
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
  }
</script>
